home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 26 / Cream of the Crop 26.iso / program / ccdl150l.zip / ALLOC / MALLOC.C < prev    next >
C/C++ Source or Header  |  1997-06-12  |  2KB  |  87 lines

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5. #include <libp.h>
  6.  
  7. void *_allocbloc = 0;
  8. int _allocflag = 0;
  9.  
  10. #pragma rundown memdelete 1
  11.  
  12. void memdelete(void)
  13. {
  14.     BLKHEAD *p = _allocbloc;
  15.     while (p) {
  16.         BLKHEAD *n = p->next;
  17.         _ll_free(p);
  18.         p = n;
  19.     }
  20. }
  21.  
  22. static int init_block(BLKHEAD **blk, size_t size)
  23. {
  24.     size_t ns = size+sizeof(size_t)+sizeof(BLKHEAD)+sizeof(FREELIST);
  25.     void *nb;
  26.     FREELIST *lp;
  27.     if (size < ALLOCSIZE)
  28.         ns = ALLOCSIZE;
  29.     nb = _ll_malloc(ns);
  30.     if (!nb)
  31.         return 0;
  32.     (*blk) = nb;
  33.     ((BLKHEAD *)nb)->next = 0;
  34.     ((BLKHEAD *)nb)->list = lp = (((char *)nb)+sizeof(BLKHEAD));
  35.     lp->next = 0;
  36.     lp->size = ns - sizeof(BLKHEAD);
  37.     return 1;
  38. }
  39. static void *split(FREELIST **flist, size_t size)
  40. {
  41.     void *p = *flist;
  42.     FREELIST *flist2;
  43.     if (size < (*flist)->size - sizeof(FREELIST)-sizeof(size_t)) {
  44.         flist2 = (char *)*flist+size+sizeof(size_t);
  45.         flist2->size = ((FREELIST *)p)->size - size-sizeof(size_t);
  46.         flist2->next = (*flist)->next;
  47.         *(long *)p = size;
  48.         *flist = flist2;
  49.     }
  50.     else {
  51.         *(long *)p = size;
  52.         (*flist) = (*flist)->next;
  53.     }
  54.     return (size_t *)p+1;
  55. }
  56. void *malloc(size_t size)
  57. {
  58.     BLKHEAD **blist;
  59.     FREELIST **flist;
  60.     void *p;
  61.     while (_allocflag)
  62.         _ll_transfer();
  63.     size +=3;
  64.     size &= 0xfffffffc;
  65.     _allocflag = 1;
  66.     blist = &_allocbloc;
  67.     while (*blist) {
  68.         flist = &(*blist)->list;
  69.         while (*flist) {
  70.             if ((*flist)->size > size+sizeof(size_t)) {
  71.                 p =split(flist,size);
  72.                 _allocflag = 0;
  73.                 return p;
  74.             }
  75.             flist = &((*flist)->next);
  76.         }
  77.         blist = &(*blist)->next;
  78.     }
  79.     if (!init_block(blist,size)) {
  80.         _allocflag = 0;
  81.         return 0;
  82.     }
  83.     flist = &(*blist)->list;
  84.     p = split(flist,size);
  85.     _allocflag = 0;
  86.     return p;
  87. }